<template>
  <div id="CollegeTab">
    <div class="contaier f14">
      <div class="df item-box" style="align-items: flex-start">
        <div class="item-title">院校省份</div>
        <div class="df" style="flex-wrap: wrap; flex: 1">
          <div class="df" style="flex-wrap: wrap">
            <div
              class="curr tabs"
              v-for="(item, index) in tabDataList.province"
              :class="isSelect('province', index, item)"
              :key="index"
            >
              <div @click="handleClick('province', index, item)">
                {{ item }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="df item-box" style="align-items: flex-start">
        <div class="item-title">院校类型</div>
        <div class="df" style="flex-wrap: wrap; flex: 1">
          <div class="df" style="flex-wrap: wrap">
            <div
              class="curr tabs"
              v-for="(item, index) in tabDataList.categories"
              :key="index"
              :class="isSelect('categories', index, item)"
            >
              <span @click="handleClick('categories', index, item)">{{
                item
              }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="df item-box" style="align-items: flex-start">
        <div class="item-title">院校层次</div>
        <div class="df" style="flex-wrap: wrap; flex: 1">
          <div class="df" style="flex-wrap: wrap">
            <div
              class="curr tabs"
              :class="isSelect('features', index, item)"
              v-for="(item, index) in tabDataList.features"
              :key="index"
            >
              <span @click="handleClick('features', index, item)">{{
                item
              }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="df item-box" style="align-items: flex-start">
        <div class="item-title">院校性质</div>
        <div class="df" style="flex-wrap: wrap; flex: 1">
          <div class="df" style="flex-wrap: wrap">
            <span
              v-for="(item, index) in tabDataList.natureType"
              :key="index"
              class="curr tabs"
              :class="isSelect('natureType', index, item)"
              ><span @click="handleClick('natureType', index, item)">{{
                item
              }}</span></span
            >

            <span
              v-show="!isSearch"
              v-for="(item, index) in tabDataList.eduLevel"
              :key="index"
              class="curr tabs"
              :class="isSelect('eduLevel', index, item)"
              ><span @click="handleClick('eduLevel', index, item)">{{
                item
              }}</span></span
            >
          </div>
        </div>
      </div>
    </div>
    <!-- search -->
    <div
      class="df"
      style="position: relative; margin: 10px 10px 0 0"
      v-if="isSearch"
    >
      <div class="df">
        <div class="f14" style="color: #9b9b9b">意向院校：</div>
        <el-select
          clearable
          v-model="collegeSearch"
          @change="handleCollegeChange"
          filterable
          remote
          no-match-text="无数据"
          no-data-text="无数据"
          reserve-keyword
          loading-text="加载中..."
          placeholder="请输入意向院校"
          :remote-method="remoteCollegeMethod"
          :loading="searchLoading"
          style="width: 240px"
        >
          <el-option
            v-for="item in collegeOptions"
            :key="item.code"
            :label="item.cnName"
            :value="item.code + '/' + item.cnName + '/' + item.provinceCode"
          />
        </el-select>
      </div>
      <el-icon class="icon-search"><Search /></el-icon>
    </div>
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue';
import { ref } from 'vue';
import bus from '../../utils/bus';
import { debounce } from 'lodash';
import { getSearchSchool } from '@/api/selectSubject/subject';
const searchLoading = ref(false);
const collegeSearch = ref('');
const collegeOptions = ref([]);
const emits = defineEmits([
  'handleClick',
  'updateHistortList',
  'handleSearchCollegeRequestData',
]);
const { tabDataList, isSearch } = defineProps({
  tabDataList: {
    type: Object,
    default: () => {},
  },
  isSearch: {
    type: Boolean,
    default: true,
  },
});

const remoteCollegeMethod = (searchdata) => {
  let requestData = {
    search: searchdata,
  };
  if (searchdata) {
    fetchSearchSchool(requestData);
  } else {
    return;
  }
};
const handleCollegeChange = (data) => {
  if (!data) {
    return;
  } else {
    let resList = data.split('/');
    const body = {
      type: 'perfer',
      item: resList[1],
      index: resList[0],
    };
    const isExist = HighLightItems.value.perfer.find(
      (v) =>
        v.item == body.item && v.type == body.type && v.index == body.index,
    );
    bus.emit('updateCollegeTableList', data);
    const arg = { type: isExist ? 0 : 1, item: body };
    if (isExist) {
      HighLightItems.value.perfer = HighLightItems.value.perfer.filter(
        (v) => v != isExist,
      );
    } else {
      HighLightItems.value.perfer.push({ index: body.index, item: body.item });
    }
    emits('updateHistortList', arg);
  }
};
const fetchSearchSchool = (data) => {
  getSearchSchool(data).then((res) => {
    if (res.data.code == 20000) {
      searchLoading.value = false;
      collegeOptions.value = res.data.data;
    }
  });
};
const HighLightItems = ref({
  province: [{ index: 0, item: '全国' }],
  categories: [{ index: 0, item: '不限' }],
  features: [{ index: 0, item: '不限' }],
  natureType: [],
  eduLevel: [],
  perfer: [],
});

const handleClickLogic = (type, index, item) => {
  try {
    // 院校省份，选全国，取消所有已选中的院校的高亮
    if (type == 'province' && index == 0 && item == '全国') {
      HighLightItems.value[type] = [{ index, item }]; // 取消所有选中的院校，并且保留全国
      bus.emit('handleRequestData', {
        data: HighLightItems.value,
        type: type,
      });
      emits('handleSearchCollegeRequestData', {
        data: HighLightItems.value,
        type: type,
      });
      emits('handleClick', {
        item: { index, item, type },
        type: 2,
      });
    } else if (type == 'categories' && index == 0 && item == '不限') {
      HighLightItems.value[type] = [{ index, item }]; // 取消所有选中的类型，并且保留不限
      bus.emit('handleRequestData', {
        data: HighLightItems.value,
        type: type,
      });
      emits('handleSearchCollegeRequestData', {
        data: HighLightItems.value,
        type: type,
      });
      emits('handleClick', {
        item: { index, item, type },
        type: 2,
      });
    } else if (type == 'features' && index == 0 && item == '不限') {
      HighLightItems.value['features'] = [{ index, item }]; // 取消所有选中的层次，并且保留不限
      HighLightItems.value['natureType'] = []; // 取消所有选中的院校性质
      bus.emit('handleRequestData', {
        data: HighLightItems.value,
        type: type,
      });
      emits('handleSearchCollegeRequestData', {
        data: HighLightItems.value,
        type: type,
      });
      emits('handleClick', {
        item: { index, item, type },
        type: 2,
      });
    }
    // 处理其他类型
    else {
      let originArray = HighLightItems.value[type];
      const isExist = originArray.find(
        (v) => v.index == index && v.item == item,
      );

      if (isExist) {
        // 删除逻辑
        HighLightItems.value[type] = originArray.filter((v) => v != isExist);
        if (HighLightItems.value[type].length == 0 && type == 'province') {
          HighLightItems.value[type] = [{ index: 0, item: '全国' }]; // 取消所有选中的院校，并且保留全国
        }
        if (HighLightItems.value[type].length == 0 && type == 'categories') {
          HighLightItems.value[type] = [{ index: 0, item: '不限' }]; // 取消所有选中的院校，并且保留不限
        }
        const grad = ['features', 'natureType'];
        if (
          grad.includes(type) &&
          grad.every((v) => HighLightItems.value[v].length == 0)
        ) {
          HighLightItems.value['features'] = [{ index: 0, item: '不限' }]; // 取消所有选中的院校，并且保留不限
        }
        emits('handleClick', {
          type: 0, // 存在 删除
          item: isExist,
        });
      } else {
        originArray.push({ index, item }); // 如果添加了新的，则全国一定会被取消高亮
        emits('handleClick', {
          type: 1, // 不存在 添加
          item: { index, item, type },
        });
        // 这些IfElse 主要是为了去掉 不限 首部的那些
        if (type == 'province') {
          originArray = originArray.filter(
            (v) => !(v.index == 0 && v.item == '全国'),
          );
        } else if (type == 'categories') {
          originArray = originArray.filter(
            (v) => !(v.index == 0 && v.item == '不限'),
          );
        } else if (type == 'features') {
          originArray = originArray.filter(
            (v) => !(v.index == 0 && v.item == '不限'),
          );
        } else if (type == 'natureType') {
          HighLightItems.value['features'] = HighLightItems.value[
            'features'
          ].filter((v) => !(v.index == 0 && v.item == '不限'));
        }
        HighLightItems.value[type] = originArray;
      }
      bus.emit('handleRequestData', {
        data: HighLightItems.value,
        type: type,
      });
      // 传递给找大学模块
      emits('handleSearchCollegeRequestData', {
        data: HighLightItems.value,
        type: type,
      });
    }
  } catch (error) {
    console.log('error:', error);
  } finally {
    searchLoading.value = false;
  }
};

const handleClick = (type, index, item) => {
  searchLoading.value = true;
  // 创建全屏加载
  debouncedHandleClick(type, index, item);
};
// 定义节流函数，500ms 内最多触发一次
const debouncedHandleClick = debounce((type, index, item) => {
  handleClickLogic(type, index, item);
}, 300);

const isSelect = (type, index, item) => {
  return HighLightItems.value[type].find(
    (v) => v.index == index && v.item == item,
  )
    ? 'active'
    : '';
};

defineExpose({
  handleClick,
});
</script>

<style lang="scss" scoped>
#CollegeTab {
  .item-title {
    width: 100px;
    margin: 10px 0;
    color: #9b9b9b;
  }
  .item-box {
    margin: 10px 0;
  }
  .tabs {
    // width: 70px;
    padding: 0 10px;
    margin: 10px 10px;
    &:hover {
      color: var(--color-text);
    }
  }
  .chiltabs {
    margin-right: 10px;
    &:hover {
      color: var(--color-text);
    }
  }
  .filter-item {
    background: #fff;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    font-size: 14px;
    line-height: 32px;
    height: 32px;
    margin: 4px;
    padding: 0 10px;
  }
}
.active {
  border: 1px solid var(--color-text);
  border-radius: 3px;
  color: var(--color-text);
}
.icon-search {
  position: absolute;
  top: 8px;
  left: 80px;
}
:deep(.el-select__wrapper) {
  padding-left: 30px;
}
</style>
